import { defineStore } from "pinia";
import { getAuth, getUserInfo } from "@/services/userManage.service";
import { getQueryStringData } from "@/utils/tool.js";
import { getTableBody } from "@/services/roleManage.service";

export const commonStore = defineStore("common-store", {
  state: () => {
    return {
      userId: decodeURIComponent(getQueryStringData("userId")),
      authList: [],
      topRole: "",
    };
  },
  getters: {
    roleType() {
      let status = false;
      if (
        this.topRole === "systemAdmin" ||
        this.userId === "admin" ||
        this.userId === "test_admin"
      ) {
        status = true;
      }
      return status;
    },
    userRoleType() {
      let status = false;
      if (this.userId === "admin" || this.userId === "test_admin") {
        status = true;
      }
      return status;
    },
  },
  actions: {
    async getAuthData(roleId) {
      const res = await getAuth(roleId);
      if (res && (res.code === 200 || res.code === 0)) {
        if (res?.result?.length > 0) {
          let arr = res.result.map((item) => JSON.parse(item));
          let arr1 = [];
          let arr2 = [];
          arr.forEach((item) => {
            arr1 = arr1.concat(item);
          });
          arr1.forEach((item) => {
            if (!arr2.some((item1) => item1.value === item.value)) {
              arr2.push(item);
            }
          });
          this.authList = arr2.map((item) => item.value);
        }
      } else {
        this.authList = [];
      }
    },
    async getAuthList() {
      const res = await getUserInfo();
      if (res && res.code === 200) {
        let selectedroles = res?.result?.userInfo?.selectedroles || "";
        if (selectedroles) {
          //功能权限页面
          // await this.getAuthData({ roleId: selectedroles });
          //上级角色
          await this.getTbodyData(selectedroles);
        }
      }
    },
    async getTbodyData(id) {
      const res = await getTableBody({
        column: "createTime",
        order: "desc",
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        id: id,
      });
      if (res.code === 0) {
        let strRole =
          res.result?.records.length > 0 && res.result?.records[0]?.topRole;
        this.topRole = JSON.parse(strRole)[0].value;
        console.log(this.topRole, "上级角色id");
      } else {
        this.topRole = "";
      }
    },
  },
});
